package com.gxljc.bear.crawler.image;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gxljc.commons.util.Pair;
import com.gxljc.bear.crawler.base.DolphinCrawlerConf;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * RefreshImage
 *
 * @author tanghaitao
 * @date 15-12-8
 */
public class RefreshImage {

    private static final RefreshImage refreshImage = new RefreshImage();

    private RefreshImage() {
    }

    public static RefreshImage getInstance() {
        return refreshImage;
    }

    public boolean ifSaveNewImgUrl(String url) {
        String localImage = "image.*?gxljc.com";
        Pattern pattern = Pattern.compile(localImage);
        Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            return true;
        }
        return false;
    }

    /**
     * 是否已经保存缩略图
     *
     * @param url
     * @return
     */
    public boolean ifSaveNewScaleImgUrl(String url) {
        if (url.contains(ImageConsts.IMAGE_SCALE_FLAG)) {
            return true;
        }
        return false;
    }

    /**
     * 获取新的img url
     *
     * @param imageUrl
     * @return
     */
    public Pair<String, Boolean> getNewImageUrlPair(String imageUrl) {
        String newImg = getNewImageUrl(imageUrl);
        if (newImg != null && !newImg.equals(imageUrl)) {
            return new Pair<String, Boolean>(newImg, false);
        } else {
            return new Pair<String, Boolean>(imageUrl, true);
        }
    }

    public List<String> listFromJson(String json) {
        Gson gson = new Gson();
        List<String> list = gson.fromJson(json, new TypeToken<List<String>>() {
        }.getType());
        return list;
    }

    public List<Map<String, String>> mapListFromJson(String json) {
        Gson gson = new Gson();
        List<Map<String, String>> list = gson.fromJson(json,
                new TypeToken<List<Map<String, String>>>() {
                }.getType());
        return list;
    }

    /**
     * pics的格式为list.toString
     *
     * @param pics
     * @return
     */
    public Pair<String, Boolean> getNewImageUrlList(String pics) {
        List<String> newPicList = new ArrayList<String>();
        List<String> picList = string2list(pics);
        boolean errorFlag = false;
        if (pics == null || pics.isEmpty()) {
            return null;
        }
        for (String pic : picList) {
            String newPic = getNewImageUrl(pic);
            if (newPic == null) {
                newPicList.add(pic);
                errorFlag = true;
            } else {
                newPicList.add(newPic);
            }
        }
        // 已处理过
        if (newPicList.isEmpty()) {
            return new Pair<String, Boolean>(null, errorFlag);
        }
        return new Pair<String, Boolean>(newPicList.toString(), errorFlag);
    }

    /**
     * string 转 list
     *
     * @param listStr
     * @return
     */
    private List<String> string2list(String listStr) {
        List<String> list = new ArrayList<String>();
        if (listStr == null) {
            return list;
        }
        listStr = listStr.replace("]", "").replace("[", "");
        if (listStr.isEmpty()) {
            return list;
        }
        if (listStr.contains(",")) {
            String[] words = listStr.split(",");
            for (String word : words) {
                list.add(word.trim());
            }
            return list;
        } else {
            list.add(listStr);
            return list;
        }
    }

    /**
     * 保存原图和缩略图，并返回缩略图地址
     *
     * @param imageUrl
     * @return
     */
    public String getNewImageUrl(String imageUrl) {
        ImageService imageService = ImageService.getInstance();
        if (imageUrl == null) {
            return imageUrl;
        }
        if (!ifSaveNewImgUrl(imageUrl)) {
            if (imageUrl.contains("\"")) {
                imageUrl = imageUrl.replaceAll("\"", "");
            }
            String newUrl = imageService.saveAndGetScaleImage(imageUrl,
                    ImageConsts.COMMON_SCALE_WIDTH,
                    ImageConsts.COMMON_SCALE_HEIGHT);
//			System.out.println("Save original and scale images : "+newUrl);
            if (newUrl.equals(ImageConsts.INEXISTENCE) || newUrl.equals(ImageConsts.IMAGE_TYPE_ERROR) || newUrl.equals(ImageConsts.IMAGE_SCALE_ERROR)) {
                return null;
            }
            return newUrl;
        } else {
            return ifSaveNewScaleImgUrl(imageUrl) == false ? saveScaleImage(imageUrl) : imageUrl;
        }
    }

    /**
     * 保存原图和缩略图，并返回缩略图地址
     *
     * @param imageUrl
     * @return
     */
    public Map<String, Object> saveOriginalImageUrl(String imageUrl) {
        return saveOriginalImageUrl(imageUrl, null);
    }

    /**
     * 保存原图和缩略图，并返回缩略图地址
     *
     * @param imageUrl
     * @return
     */
    public Map<String, Object> saveOriginalImageUrl(String imageUrl, Map<String, String> property) {
        ImageService imageService = ImageService.getInstance();
        if (StringUtils.isEmpty(imageUrl)) {
            return null;
        }
        if (!checkImgUrl(imageUrl)) {
            if (imageUrl.contains("\"")) {
                imageUrl = imageUrl.replaceAll("\"", "");
            }
            Map<String, Object> newUrlMap = imageService.saveAndGetImage2UrlAndSize(imageUrl, property);
            String status = (String) newUrlMap.get(ImageConsts.IMAGE_MAP_NAME.STATUS.getValue());
            if (status.equals(ImageConsts.INEXISTENCE) || status.equals(ImageConsts.IMAGE_TYPE_ERROR) || status.equals(ImageConsts.IMAGE_SCALE_ERROR)) {
                return null;
            }
            return newUrlMap;
        } else {
            return imageService.imageGenMap(imageUrl, 0, 0, ImageConsts.NOT_CHANGE);
        }
    }

    //检查url是否已经本地化存储
    public boolean checkImgUrl(String url) {
        Configuration conf = DolphinCrawlerConf.getInstance();
        String urlDomain1 = conf.get(ImageConsts.PARAM_IMAGEWEB_EXPLAIN_DOMAIN);
        String urlDomain2 = "image.*?gxljc.com";
        String[] array = new String[]{urlDomain1, urlDomain2};
        for (String d : array) {
            Pattern pattern = Pattern.compile(d);
            Matcher matcher = pattern.matcher(url);
            if (matcher.find()) {
                return true;
            }
        }
        return false;
    }


    /**
     * 原尺寸图片已存在，生成缩略图，并返回缩略图地址
     *
     * @param imageUrl
     * @return
     */
    public String saveScaleImage(String imageUrl) {
        ImageService imageService = ImageService.getInstance();
        if (imageUrl == null) {
            return imageUrl;
        }
        if (imageUrl.contains("\"")) {
            imageUrl = imageUrl.replaceAll("\"", "");
        }
        String newUrl = imageService.saveScaleImage(imageUrl,
                ImageConsts.COMMON_SCALE_WIDTH,
                ImageConsts.COMMON_SCALE_HEIGHT);
        System.out.println("scaleImage:\t" + newUrl);
        if (newUrl.equals(ImageConsts.INEXISTENCE)
                || newUrl.equals(ImageConsts.IMAGE_TYPE_ERROR) || newUrl.equals(ImageConsts.IMAGE_SCALE_ERROR)) {
            return null;
        }
        System.out.println("Save Scale image : " + newUrl);
        return newUrl;
    }
}
